@echo off
chcp 65001 > nul

REM 端口切换脚本 - Windows版本
REM 功能：快速更改前后端端口配置
REM 使用方法：change-port.bat 8001

if "%1"=="" (
    echo 🔧 端口切换工具
    echo ======================================
    echo 用法: change-port.bat ^<新端口号^>
    echo 示例: change-port.bat 8001
    echo ======================================
    echo 当前配置:
    for /f "tokens=4" %%i in ('findstr "PORT:" backend\core\config.py') do echo   后端端口: %%i
    if exist webui\.env.local (
        for /f "tokens=2 delims=:" %%i in ('findstr "localhost" webui\.env.local') do echo   前端API: http:%%i
    ) else (
        echo   前端API: 未配置
    )
    exit /b 1
)

set NEW_PORT=%1

REM 验证端口号
echo %NEW_PORT%| findstr /r "^[0-9][0-9]*$" >nul
if errorlevel 1 (
    echo ❌ 错误：端口号必须是数字
    exit /b 1
)

if %NEW_PORT% LSS 1024 (
    echo ❌ 错误：端口号必须大于1024
    exit /b 1
)

if %NEW_PORT% GTR 65535 (
    echo ❌ 错误：端口号必须小于65535
    exit /b 1
)

echo 🔧 正在切换到端口 %NEW_PORT%...

REM 更新后端配置
powershell -Command "(Get-Content backend\core\config.py) -replace 'PORT: int = [0-9]+', 'PORT: int = %NEW_PORT%' | Set-Content backend\core\config.py"

REM 更新前端环境变量
echo NEXT_PUBLIC_API_BASE_URL=http://localhost:%NEW_PORT% > webui\.env.local

echo ✅ 端口切换完成！
echo ======================================
echo 新配置:
echo   后端端口: %NEW_PORT%
echo   前端API: http://localhost:%NEW_PORT%
echo ======================================
echo 💡 请重启服务以使配置生效：
echo   stop.bat ^&^& start.bat 